﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Castle.DynamicProxy;
using CNKI.TPI.Web.Base;
using CNKI.TPI.Web.Search.IBLL;
using CNKI.TPI.Web.Search.Model;
using System.Collections;
using System.Text;
using System.Web.SessionState;
using CNKI.TPI.Web.UI.Filters;
using CNKI.TPI.Web.Admin.IBLL;

namespace CNKI.TPI.Web.UI.Controllers.Search
{
    [SessionState(SessionStateBehavior.ReadOnly)]
    public class SingleSearchController : BaseController
    {
        int dbID = 0;
        string dbName = "";
        string displayDBName = "";
        string topicCLSNodeCode = "";
        string topicCLSCode = "";
        int categoryType = 0;
        bool isAutoLoad = ConfigHelper.IsAutoShowResult();
        int searchLogID = -1;
        SearchType searchType = SearchType.TPI;
        

        SYS_CMS_DATABASE dbinfo = null;
        MediaType mediaType = MediaType.Doc;

        INaviService naviService = null;
        ISearchService searchService = null;
        IUserCenterService centerService = null;
        public SingleSearchController(INaviService naviService, ISearchService searchService, IUserCenterService centerService)
        {
            this.naviService = generator.CreateInterfaceProxyWithTarget<INaviService>(naviService, new IInterceptor[] { new LogInterceptor() });
            this.searchService = generator.CreateInterfaceProxyWithTarget<ISearchService>(searchService, new IInterceptor[] { new LogInterceptor() });
            this.centerService = generator.CreateInterfaceProxyWithTarget<IUserCenterService>(centerService, new IInterceptor[] { new LogInterceptor() });
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            //相似词搜索网址
            //ViewBag.smartWordAddress = ConfigHelper.GetAppSettingsValue("smartWordAddress");
            LoadParameter();
            //分类类型
            IList<CLS> categoryTypeList = naviService.GetCategoryType(dbName, dbID);
            ViewBag.CategoryType = categoryTypeList;

            //检索字段4，
            IList<SYS_CMS_DATABASE_PUBLISH_FIELD> searchField = searchService.GetSearchFieldList(dbID);
            if ((searchField == null || searchField.Count == 0) && dbinfo.DatabaseType == 11)
            {
                searchField = new List<SYS_CMS_DATABASE_PUBLISH_FIELD>();
                searchField.Add(new SYS_CMS_DATABASE_PUBLISH_FIELD { FieldName = "标题", FieldDispName = "标题" });
                searchField.Add(new SYS_CMS_DATABASE_PUBLISH_FIELD { FieldName = "作者", FieldDispName = "作者" });
                searchField.Add(new SYS_CMS_DATABASE_PUBLISH_FIELD { FieldName = "发布单位", FieldDispName = "发布单位" });
                searchField.Add(new SYS_CMS_DATABASE_PUBLISH_FIELD { FieldName = "全文", FieldDispName = "全文" });
            }
            ViewBag.SearchField = searchField;

            ViewBag.DbID = dbID;
            ViewBag.DbName = dbName;
            ViewBag.MediaType = (int)mediaType;
            ViewBag.TopicCLSCode = topicCLSCode;
            ViewBag.TopicCLSNodeCode = topicCLSNodeCode;
            ViewBag.AutoLoad = isAutoLoad.ToString();
            //if (mediaType == MediaType.Doc || mediaType == MediaType.Ebook)
            //{
            ViewBag.MediaResource = naviService.GetDataBaseList();
            //}
            //else
            //{
            //    ViewBag.MediaResource = naviService.GetMediaResourceList();
            //}
            ViewBag.DisplayDBName = displayDBName;

            //用户行为历史
            if (SessionHelper.GetUserInfo() != null && ConfigHelper.IsShowUserHistoryEnabled()
            && ((ConfigHelper.IsAnonymousControlEnabled() && SessionHelper.GetUserInfo().UserCode.ToUpper() != ConfigHelper.GetAnonymousAccount().ToUpper())
            || !ConfigHelper.IsAnonymousControlEnabled()))
            {
                int count = 0;//总条数
                              //浏览历史      
                DataTable dtView = centerService.GetViewPage("", "", null, null, 1, 5, out count);
                //检索历史
                DataTable dtSearch = centerService.GetSearchPage("", null, null, 1, 5, out count);
                //下载历史
                DataTable dtDown = centerService.GetDownPage("", "", null, null, 1, 5, out count);
                ViewBag.DTView = dtView;
                ViewBag.DTSearch = dtSearch;
                ViewBag.DTDown = dtDown;
            }

            //根据用户行为还原检索状态
            ViewBag.SearchLogID = searchLogID;
            string conditionType = "";
            string categoryNodeCode = "";
            int clsID = -1;
            if (-1 != searchLogID)
            {
                IList<SearchQuery> searchQueryList = new List<SearchQuery>();
                
                string order;
                centerService.GetSingleSearchLogDetail(dbID.ToString(), dbName, searchType, searchLogID, searchQueryList, out clsID, out categoryNodeCode, out order);
                ViewBag.SearchQuery = searchQueryList;
                IDictionary<string, int> conditionTypeList = new Dictionary<string, int>();
                foreach (SearchQuery item in searchQueryList)
                {
                    conditionTypeList.Add(item.Key, (int)item.ConditionType);
                }
                conditionType = SerializeHelper.Serialize(conditionTypeList);

                if (!string.IsNullOrEmpty(order))
                {
                    string sortField = order.Substring(0, order.LastIndexOf(' '));
                    string sortType = order.Substring(order.LastIndexOf(' ') + 1);
                    ViewBag.SortFiledNow = sortField;
                    ViewBag.SortDescAsc = sortType;
                }
                ViewBag.AutoLoad = "True";
            }
            ViewBag.CategoryCLSID = clsID;
            ViewBag.ConditionType = conditionType;
            ViewBag.CategoryNodeCode = categoryNodeCode;

            //分类明细
            if (null != categoryTypeList && categoryTypeList.Count > 0)
            {
                IList<CLS_NODE> categoryList = null;
                if (categoryTypeList.Where(c => c.SysID == clsID).ToList().Count > 0)
                {
                    categoryList = naviService.GetCategoryList(dbName, clsID, dbID);
                }
                else
                {
                    categoryList = naviService.GetCategoryList(dbName, categoryTypeList[0].SysID, dbID);
                }
                ViewBag.CategoryList = categoryList;
            }
            else
            {
                ViewBag.CategoryList = new List<CLS_NODE>();
            }
            return View();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public ActionResult GetCategroyList()
        {
            LoadParameter();
            IList<CLS_NODE> categoryList = naviService.GetCategoryList(dbName, categoryType, dbID);
            ViewBag.CategoryList = categoryList;
            return PartialView("CategoryList");
        }

        public JsonResult GetCategroyChilds()
        {
            LoadParameter();
            string code = "";
            if (!String.IsNullOrEmpty(Request.QueryString["code"]))
            {
                code = Request.QueryString["code"].ToString();
            }
            IList<CLS_NODE> categoryList = naviService.GetChildrenCategoryList(dbName, categoryType, code, dbID);
            var res = new JsonResult();
            res.Data = categoryList;
            res.JsonRequestBehavior = JsonRequestBehavior.AllowGet;//允许使用GET方式获取，否则用GET获取是会报错。 
            return res;

        }
        //public ActionResult GetMoreList()
        //{
        //    return View("../DocResource/DocResource");
        //}

        /// <summary>
        /// 
        /// </summary>
        /// <param name="form"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateInput(false)]
        [SecurityActionFilter]
        public ActionResult Search(FormCollection form)
        {
            int pageSize = 12;//每页显示记录数
            int pageIndexNow = 1;// 当前页    
            int sumCount = 0;//总条数
            int sumPage = 0;//一共多少页
            int disPgae = 8;  //默认显示页数，当页数大于该数值时，按规定格式显示
            string strOrder = "";
            ViewBag.listAbstract = "list";//列表显示模式
            if (Request["listOrabst"] != null && Request["listOrabst"].ToString() != "")
            {
                ViewBag.listAbstract = Request["listOrabst"];
            }
            IList<SearchQuery> searchQuery = new List<SearchQuery>();
            string checkedCatID = Request["beforecheckedCatID"];
            int currentSubid = int.Parse(Request["currentSubid"]);
            int selectedCatTypeID = 0;
            if (Request["beforeselectedCatTypeID"] != null && Request["beforeselectedCatTypeID"] != "")
            {
                selectedCatTypeID = int.Parse(Request["beforeselectedCatTypeID"]);
            }
            dbID = int.Parse(Request["dbID"]);

            dbName = Request["dbName"];
            topicCLSCode = Request["topicCLSCode"];
            topicCLSNodeCode = Request["topicCLSNodeCode"];
            //mediaType = (MediaType)int.Parse(Request["MediaType"]);

            dbinfo = naviService.GetDatabase(dbName, 0);
            if (!String.IsNullOrEmpty(Request.QueryString["MediaType"]))
            {
                mediaType = (MediaType)int.Parse(Request.QueryString["MediaType"]);
            }
            else
            {
                if (dbinfo != null && dbinfo.SysID != 0)
                {
                    mediaType = ResourceHelper.ConvertMediaType(dbinfo.TemplateID);
                }
            }
            if (mediaType == MediaType.Doc)
            {
                pageSize = 10;
            }
            pageIndexNow = int.Parse(Request["pageIndexNow"]);

            string conditionValue = string.IsNullOrEmpty(Request["beforeConditionValue"]) ? "" : Request["beforeConditionValue"];
            int Querystr = string.IsNullOrEmpty(Request["beforeQueryValue"]) ? 0 : int.Parse(Request["beforeQueryValue"].ToString());
            searchQuery.Add(new SearchQuery(Request["beforeConditionKey"], conditionValue, (ConditionType)Querystr));
            //dbinfo = searchService.GetDataByID(dbID);
            //if (dbinfo.RecordCheckPubFlag == 1 && dbinfo.SearchType == (int)SearchType.TPI) //审核标识
            //{
            //    searchQuery.Add(new SearchQuery("SYS_FLD_CHECKSTATE", "2", ConditionType.Eq,SearchMatchType.And));
            //}
            string contype = "";
            string conkey = "";
            for (int i = 1; i <= currentSubid; i++)
            {
                //conditionValue = string.IsNullOrEmpty(Request["beforeConditionValue" + i]) ? "" : "*" + Request["beforeConditionValue" + i];
                Querystr = string.IsNullOrEmpty(Request["beforeQueryValue" + i]) ? 0 : int.Parse(Request["beforeQueryValue" + i].ToString());//模糊精确
                conditionValue = string.IsNullOrEmpty(Request["beforeConditionValue" + i]) ? "" : Request["beforeConditionValue" + i];//值
                contype = string.IsNullOrEmpty(Request["beforeConditionType" + i]) ? "0" : Request["beforeConditionType" + i];//and or
                conkey = string.IsNullOrEmpty(Request["beforeConditionKey" + i]) ? "" : Request["beforeConditionKey" + i];//关键词

                searchQuery.Add(new SearchQuery(conkey, conditionValue, (ConditionType)Querystr, (SearchMatchType)int.Parse(contype)));
            }

            strOrder = GetSort(dbID);
            //检索
            string query = "";
            DataSet ds = searchService.SingleSearch(dbID, dbName, searchQuery, selectedCatTypeID, checkedCatID, "", strOrder, pageIndexNow, pageSize, out query, topicCLSCode: topicCLSCode, topicCLSNodeCode: topicCLSNodeCode);
            if (!string.IsNullOrEmpty(query))
            {
                LogOpr.Search(dbID.ToString(), dbName, query, strOrder, "SingleSearch", "", topicCLSCode, topicCLSNodeCode);
            }
            if (ds.Tables.Count > 0)
            {
                ViewBag.SearchResult = ds.Tables[0];
                if (ds.Tables["infos"].Rows.Count > 0)
                {
                    sumCount = int.Parse(ds.Tables["infos"].Rows[0]["count"].ToString());//总条数
                }
                sumPage = sumCount / pageSize; //一共多少页
                if (sumCount % pageSize != 0)
                {
                    sumPage = sumPage + 1;
                }
                ViewBag.TotalPage = sumPage;
                ColumnAliasHelper objhelp = new ColumnAliasHelper();
                ViewBag.PageList = objhelp.GetPageList(pageIndexNow, sumPage, disPgae);
                ViewBag.PageNow = pageIndexNow;//当前页
                ViewBag.PageSize = pageSize;
                ViewBag.ResultCount = sumCount.ToString("N0");
                ViewBag.ResultColumnInfo = ds.Tables["ColumnInfo"];
            }
            ViewBag.DbID = dbID;
            ViewBag.DbName = dbName;
            ViewBag.SearchType = (SearchType)dbinfo.SearchType;
            ViewBag.MediaType = (int)mediaType; //跳转到详细页区分类型用
            ////是否有下载权限
            //bool flage = SessionHelper.HasDownloadRight(dbID);
            //ViewBag.HasDown = flage;

            //分类类型
            if (Request["SearchFrom"] != "Topic")
            {
                IList<CLS> categoryTypeList = naviService.GetCategoryType(dbName, dbID);
                ViewBag.CategoryType = categoryTypeList;
            }
            else
            {
                ViewBag.CategoryType = null;
            }

            ViewBag.DisplayDBName = dbinfo.DatabaseName; 
            string list = GetListByType(mediaType);
            if (list == "DocList")
            {
                //分类
                DataTable dt = centerService.GetFavoriteCategory();
                ViewBag.FavCateList = dt;

                //收藏数据
                DataTable dtfav= centerService.GetFavFolderList(dbName);
                string recordidstr = "";
                if (dtfav != null && dtfav.Rows.Count > 0)
                {
                    foreach (DataRow dr in dtfav.Rows)
                    {
                        recordidstr += dr["RecordID"].ToString();
                        recordidstr += ",";
                    }
                }
                ViewBag.FavList = ","+recordidstr;
            }
            return PartialView(list);
        }
        /// <summary>
        /// 页面排序
        /// </summary>
        /// <param name="dbID"></param>
        /// <returns></returns>
        private string GetSort(int dbID)
        {
            string strOrder = "";
            string sortstr = "desc";//默认按降序
            IList<SYS_CMS_DATABASE_PUBLISH_FIELD> listSort = searchService.GetSortFieldList(dbID);//排序字段集合
            SYS_CMS_DATABASE obj = searchService.GetDataByID(dbID);
            if (obj != null)
            {
                sortstr = obj.OrderType == 1 ? "asc" : "desc";
            }
            if (listSort != null && listSort.Count > 0) //初始化
            {
                ViewBag.SortField = listSort;
                ViewBag.SortFiledNow = listSort[0].FieldName;//当前排序字段
                ViewBag.SortFiledInit = listSort[0].FieldName;//默认排序字段
                strOrder = listSort[0].FieldName + " " + sortstr;
            }
            else if (dbinfo.DatabaseType == 11)
            {
                listSort = new List<SYS_CMS_DATABASE_PUBLISH_FIELD>();
                listSort.Add(new SYS_CMS_DATABASE_PUBLISH_FIELD { FieldName = "发布时间", FieldDispName = "发布时间" });
                ViewBag.SortField = listSort;
                ViewBag.SortFiledNow = listSort[0].FieldName;//当前排序字段
                ViewBag.SortFiledInit = listSort[0].FieldName;//默认排序字段
            }
            else
            {
                ViewBag.SortField = null;
                ViewBag.SortFiledNow = "";//
            }

            ViewBag.SortDescAsc = sortstr;
            ViewBag.SortDescInit = sortstr;//默认排序

            if (Request["sortField"] != null && Request["sortField"].ToString() != "")//如果页面有值就重新赋值
            {
                ViewBag.SortFiledNow = Request["sortField"];
                if (Request["sortDescAsc"] != "")
                {
                    ViewBag.SortDescAsc = Request["sortDescAsc"];
                }
                strOrder = Request["sortField"] + " " + Request["sortDescAsc"];
            }
            return strOrder;
        }
        /// <summary>
        /// 获取类型对应的子页面
        /// </summary>
        /// <param name="mediaType"></param>
        /// <returns></returns>
        private string GetListByType(MediaType mediaType)
        {
            switch (mediaType)
            {
                case MediaType.Video:
                    return "VideoList";
                case MediaType.Audio:
                    return "AudioList";
                case MediaType.Pic:
                    return "PicList";
                case MediaType.Ebook:
                    return "E_Book";
                case MediaType.Doc:
                default:
                   
                    return "DocList";
            }
        }
        /// <summary>
        /// 
        /// </summary>
        private void LoadParameter()
        {
            if (!String.IsNullOrEmpty(Request.QueryString["id"]))
            {
                dbID = int.Parse(Request.QueryString["id"]);
            }
            if (!String.IsNullOrEmpty(Request.QueryString["name"]))
            {
                dbName = Request.QueryString["name"];
                  if (dbID == 0)
                {
                    dbID = naviService.GetDatabase(dbName, 0).SysID;
                }
            }
            if (!String.IsNullOrEmpty(Request.QueryString["topicCLSCode"]))
            {
                topicCLSCode = Request.QueryString["topicCLSCode"];
            }
            if (!String.IsNullOrEmpty(Request.QueryString["topicCLSNodeCode"]))
            {
                topicCLSNodeCode = Request.QueryString["topicCLSNodeCode"];
            }
            dbinfo = naviService.GetDatabase(dbName, 0);
            if (!String.IsNullOrEmpty(Request.QueryString["mediaType"]))
            {
                mediaType = (MediaType)int.Parse(Request.QueryString["mediaType"]);
            }
            else
            {
                if (dbinfo != null && dbinfo.SysID != 0)
                {
                    mediaType = ResourceHelper.ConvertMediaType(dbinfo.TemplateID); 
                }
            }
            if (!String.IsNullOrEmpty(Request.QueryString["type"]))
            {
                categoryType = int.Parse(Request.QueryString["type"]);
            }
            if (!String.IsNullOrEmpty(Request.QueryString["dbName"]))
            {
                dbName = Request.QueryString["dbName"];
                if (dbID == 0)
                {
                    dbID = naviService.GetDatabase(dbName, 0).SysID;
                }
            }
            if (!String.IsNullOrEmpty(Request.QueryString["displayDBName"]))
            {
                displayDBName = Request.QueryString["displayDBName"];
            }
            if (!String.IsNullOrEmpty(Request.QueryString["autoLoad"]))
            {
                isAutoLoad = Request.QueryString["autoLoad"] == "1"?true:false;
            }
            if (!String.IsNullOrEmpty(Request.QueryString["searchLog"]))
            {
                searchLogID = int.Parse(Request.QueryString["searchLog"]);
            }
            if (!String.IsNullOrEmpty(Request.QueryString["searchType"]))
            {
                searchType = (SearchType)int.Parse(Request.QueryString["searchType"].ToString());
            }
        }

        /// <summary>
        /// 根据记录ID获取文件信息
        /// </summary>
        /// <param name="recordID"></param>
        /// <param name="dbName"></param>
        /// <param name="mediaType"></param>
        /// <returns></returns>
        public JsonResult GetFilesByRecordID(int recordID, string dbName, int mediaType, int dbID, int downtype)
        {
            IList<METADATA_FILE> listfile = searchService.GetFile(recordID, dbName);

            if (listfile != null && listfile.Count > 0)
            {
                foreach (METADATA_FILE item in listfile)
                {
                    item.DOWNLOADURL = ResourceHelper.GetFileDownloadURL(dbID, item.SYSID, recordID, downtype); //下载地址
                }
            }
            var res = new JsonResult();
            res.Data = listfile;
            res.JsonRequestBehavior = JsonRequestBehavior.AllowGet;//允许使用GET方式获取，否则用GET获取是会报错。 
            return res;

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="dbCode"></param>
        /// <param name="fieldName"></param>
        /// <returns></returns>
        public JsonResult GetFieldMatchTypeList(string dbCode, string fieldName)
        {
            Dictionary<string,string> listfile = searchService.GetFieldMatchTypeList(dbCode, fieldName);
            var res = new JsonResult();
            res.Data = listfile;
            res.JsonRequestBehavior = JsonRequestBehavior.AllowGet;//允许使用GET方式获取，否则用GET获取是会报错。 
            return res;
        }
    }
}
